﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FinalPointSet.Model.Constant;
using FinalPointSet.Model.Constant.Message;
using FinalPointSet.Model.Constants;
using FinalPointSet.Model.Manager;
using FinalPointSet.Model.Model;
using FinalPointSet.Model.Model.FieldMapping;
using ICSharpCode.AvalonEdit.Highlighting;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using static FinalPointSet.Model.Manager.MessageManager;

namespace FinalPointSet.ViewModel.Page.FieldMapping
{
    public partial class TemplateSettingPageViewModel : ObservableObject, IDisposable
    {
        /// <summary>
        /// 数据源映射规则
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<FormatTemplate> _FormatTemplates = new();

        /// <summary>
        /// 代码高亮
        /// </summary>
        [ObservableProperty]
        private IHighlightingDefinition? _HighlightingDefinition;

        public TemplateSettingPageViewModel()
        {
            //初始化代码高亮
            HighlightingDefinition = AssetManager.Instance.GetObjectListElementValueByKey<IHighlightingDefinition>(Path.HighLightDefinition, "SQL");

            //初始化数据源集合资源
            InitDataSources();

            //监听数据源集合资源变化
            AssetManager.Instance.OnJsonObjectListUpdate += OnDataSourceUpdate;
        }

        private void OnDataSourceUpdate(Type type)
        {
            if (type == typeof(DataSource))
                InitDataSources();
        }

        /// <summary>
        /// 初始化数据源集合资源
        /// </summary>
        private void InitDataSources()
        {
            FormatTemplates = new(DataSourceMappingHelper.GetFormatTemplates());
        }

        /// <summary>
        /// 保存
        /// </summary>
        [RelayCommand]
        private void Save()
        {
            AssetManager.Instance.UpdateJsonObjectList(FormatTemplates.ToList());
            AssetManager.Instance.SaveJsonObjectList<FormatTemplate>(new FormatTemplateConverter());
            Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Success, $"保存数据源生成模板成功!"));
        }

        public void Dispose()
        {
            AssetManager.Instance.OnJsonObjectListUpdate -= OnDataSourceUpdate;
        }
    }
}
